<template>
  <div class="detail-page">
    <h2>客户详情</h2>
    <el-card shadow="hover">
      <el-descriptions :column="2" border v-loading="loading">
        <el-descriptions-item label="序号">{{ customer.id }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">
          <el-input v-if="isEditing" v-model="customer.name"></el-input>
          <span v-else>{{ customer.name }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="类型">
          <el-select
            v-if="isEditing"
            v-model="data.request.type"
            placeholder="客户类别"
            size="large"
            style="width: 240px"
            :loading="loadingOptions"
          >
            <el-option
              v-for="item in data.type_list"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <span v-else>{{ customer.type }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="地址">
          <el-input v-if="isEditing" v-model="customer.address"></el-input>
          <span v-else>{{ customer.address }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="客户来源">
          <el-select
            v-if="isEditing"
            v-model="data.request.source"
            placeholder="客户来源"
            size="large"
            style="width: 240px"
            :loading="loadingOptions"
          >
            <el-option
              v-for="item in data.source_list"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <span v-else>{{ customer.source }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="电话">
          <el-input v-if="isEditing" v-model="customer.phone"></el-input>
          <span v-else>{{ customer.phone }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(customer.status)">
            {{ getStatusText(customer.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="下次联系时间">
          <el-date-picker v-if="isEditing" v-model="customer.next_time" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
          <span v-else>{{ formatTime(customer.next_time) }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="跟进时间">
          <span>{{ formatTime(customer.follow_time) }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="进入公海时间">
          <el-date-picker v-if="isEditing" v-model="customer.seas_time" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
          <span v-else>{{ formatTime(customer.seas_time) }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="描述">
          <el-input v-if="isEditing" v-model="customer.explain" type="textarea"></el-input>
          <span v-else>{{ customer.explain }}</span>
        </el-descriptions-item>
      </el-descriptions>
      <div class="action-buttons">
        <el-button v-if="!isEditing" type="primary" @click="toggleEdit">修改</el-button>
        <template v-if="isEditing">
          <el-button type="success" @click="saveChanges">保存</el-button>
          <el-button type="warning" @click="cancelEdit">取消</el-button>
        </template>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { useRoute } from 'vue-router';
import { Get_Customer_Details, Update_Customer_Details } from '@/api/customer';
import type { Customer_Detail_Data } from '@/utils/types';
import dayjs from 'dayjs';
import { Get_Origin, Get_Type } from "@/api/customer/index";
import { notice } from '@/utils/notice';

const route = useRoute();

const customer = ref<Customer_Detail_Data>({
  id: '',
  name: '',
  type: '',
  address: '',
  source: '',
  phone: '',
  level: '',
  status: 0,
  next_time: '',
  follow_time: '',
  seas_time: '',
  explain: '',
});

const originalCustomer = ref<Customer_Detail_Data>({
  id: '',
  name: '',
  type: '',
  address: '',
  source: '',
  phone: '',
  level: '',
  status: 0,
  next_time: '',
  follow_time: '',
  seas_time: '',
  explain: '',
});

const data = reactive({
  isFirst: true,
  source_list: [] as Array<{ id: string; name: string }>,
  type_list: [] as Array<{ id: string; name: string }>,
  request: {
    name: "",
    phone: "",
    type: "",
    source: "",
    address: "",
    next_time: "",
    seas_time: "",
    dexplain: "",
  },
});

const loading = ref(true);
const isEditing = ref(false);
const loadingOptions = ref(false);

onMounted(async () => {
  try {
    const res = await Get_Customer_Details({
      id: route.params.id.toString(),
    });
    if (res.code === 0) {
      customer.value = res.data.data[0];
      originalCustomer.value = { ...res.data.data[0] };
    }
  } catch (error) {
    console.error('获取客户详情失败', error);
  } finally {
    loading.value = false;
  }
});

const toggleEdit = async () => {
  loadingOptions.value = true;
  try {
    const res = await Get_Origin({
      keys: ["customer_source"],
    });
    if (res.code === 0) {
      data.source_list = res.data.data;
    }

    const res1 = await Get_Type({
      keys: ["origin"],
    });
    if (res1.code === 0) {
      data.type_list = res1.data.data;
    }

    // 确保 customer 中的 type 和 source 是字符串类型
    customer.value.type = String(customer.value.type);
    customer.value.source = String(customer.value.source);

    isEditing.value = !isEditing.value;
  } catch (error) {
    console.error('获取选项数据失败', error);
  } finally {
    loadingOptions.value = false;
  }
};

const saveChanges = async () => {
  loading.value = true;
  try {
    const res = await Update_Customer_Details({
      id: customer.value.id,
      name: customer.value.name,
      type: data.request.type,
      address: customer.value.address,
      source: data.request.source,
      phone: customer.value.phone,
      next_time: customer.value.next_time,
      seas_time: customer.value.seas_time,
      explain: customer.value.explain,
    });
    if (res.code === 0) {
      isEditing.value = false;
      notice({ code: 0, message: '客户信息更新成功' });
      originalCustomer.value = { ...customer.value }; // 更新原始数据

    } else {
      notice(res);
    }
  } catch (error) {
    console.error('更新客户信息失败', error);
    notice({ code: -1, message: '更新客户信息失败' });
  } finally {
    loading.value = false;
  }
  isEditing.value = false;
};

const cancelEdit = () => {
  // 恢复原始数据
  customer.value = { ...originalCustomer.value };
  isEditing.value = false;
};

const formatTime = (time: string) => {
  return time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '-';
};

const getStatusType = (status: number) => {
  switch (status) {
    case 1:
      return 'primary';
    case 2:
      return 'success';
    default:
      return 'warning';
  }
};

const getStatusText = (status: number) => {
  switch (status) {
    case 1:
      return '进行中';
    case 2:
      return '已转化';
    default:
      return '公海';
  }
};

</script>

<style scoped>
.detail-page {
  padding: 20px;
}

.el-card {
  margin-top: 20px;
  padding: 20px;
}

.el-descriptions {
  margin-top: 20px;
}

.el-descriptions .el-descriptions__body .el-descriptions__cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 48px; /* 设置固定高度 */
}

.el-descriptions .el-descriptions__body .el-descriptions__cell .el-descriptions__label {
  font-weight: bold;
  width: 150px; /* 固定标签宽度 */
}

.el-descriptions .el-descriptions__body .el-descriptions__cell .el-descriptions__content {
  flex-grow: 1;
  text-align: left;
}

.action-buttons {
  margin-top: 20px;
  text-align: right;
}
</style>
